const express = require('express')
const bodyParser = require("body-parser")
const session = require('express-session')
const http = require('http')

// 文件上传相关
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

// 静态资源
app.use(express.static('./uploads'))

// 跨域
const cors = require('cors')
app.use(cors())

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false,
    cookie: {
        // secure: true,
        maxAge: 1000 * 60 * 3
    }
}))

// 解析数据
app.use(bodyParser.json())
app.use(express.urlencoded({extended: true}))

// 封装res.send()方法
app.use((req, res, next) => {
    res.cc = function(err, code = 400) {
        res.send({
            code: err instanceof Error ? 500 : code,
            message: err instanceof Error ? "服务器异常" : err
        })
    }
    next()
})

// 解析token
const secretKey = 'ethink' 
const expressJWT = require('express-jwt')
app.use(expressJWT({secret: secretKey, algorithms: ['HS256']}).unless({path: [/\/api\/v1\/account/]}))

// const server = http.createServer(app)

// 引入路由
const accountRouter = require('./router/account')
app.use('/api/v1/account', accountRouter)
// 用户信息
const userRouter = require('./router/user')
app.use('/api/v1/user', userRouter)
// 平台管理
const homeRouter = require('./router/home')
app.use('/api/v1/home', homeRouter)
// 大数据
const dataRouter = require('./router/data')
app.use('/api/v1/data', dataRouter)
// 文件上传
const uploadRouter = require('./router/upload')
app.use('/api/v1/upload', uploadRouter)

// 错误处理，必须在所有路由之后
app.use((err, req, res, next) => {
    // token解析失败导致的错误
    if (err.name === 'UnauthorizedError') return res.cc('token认证失败', 401)
    // 其他原因导致的错误
    res.cc(err)
})

const server = app.listen(30651, () => {
    console.log("server is running at http://127.0.0.1:30651");
})

// websocket
const { initSocket } = require('./socket/ws')
initSocket(server);